// pages/orders/orders.js
const app = getApp()
const auth = require('../../utils/auth')

Page({
  data: {
    activeTab: 'pending',
    tabs: [
      { id: 'pending', name: '待烹饪', count: 0 },
      { id: 'completed', name: '已完成', count: 0 }
    ],
    pendingOrders: [],
    completedOrders: [],
    stats: {
      todayCount: 0,
      pendingCount: 0,
      completedCount: 0
    },
    isAuthenticated: false,
    currentUser: null
  },

  onLoad(options) {
    this.checkAuthentication()
    if (options.tab) {
      this.setData({ activeTab: options.tab })
    }
    this.loadOrders()
    this.loadStats()
  },

  onShow() {
    this.checkAuthentication()
    this.loadOrders()
    this.loadStats()
  },

  // 检查认证状态
  checkAuthentication() {
    // 首先检查是否已经有认证状态
    const currentUser = auth.getCurrentUser()
    if (currentUser) {
      this.setData({
        isAuthenticated: true,
        currentUser: currentUser
      })
      return
    }
    
    // 如果没有认证状态，重新检查
    auth.checkAuthentication()
      .then(user => {
        auth.setCurrentUser(user)
        this.setData({
          isAuthenticated: true,
          currentUser: user
        })
      })
      .catch(err => {
        this.setData({
          isAuthenticated: false,
          currentUser: null
        })
        wx.showModal({
          title: '需要身份验证',
          content: '使用订单管理功能需要先进行身份验证',
          showCancel: false,
          success: () => {
            wx.switchTab({
              url: '/pages/home/home'
            })
          }
        })
      })
  },

  // 加载订单列表
  loadOrders() {
    if (!this.data.isAuthenticated) {
      this.setData({
        pendingOrders: [],
        completedOrders: [],
        'tabs[0].count': 0,
        'tabs[1].count': 0
      })
      return
    }
    
    const db = wx.cloud.database()
    
    // 加载待烹饪订单
    db.collection('orders')
      .where({
        status: 'pending'
      })
      .orderBy('createTime', 'desc')
      .get()
      .then(res => {
        this.setData({
          pendingOrders: res.data,
          'tabs[0].count': res.data.length
        })
      })
    
    // 加载已完成订单
    db.collection('orders')
      .where({
        status: 'completed'
      })
      .orderBy('createTime', 'desc')
      .get()
      .then(res => {
        this.setData({
          completedOrders: res.data,
          'tabs[1].count': res.data.length
        })
      })
  },

  // 加载统计数据
  loadStats() {
    const db = wx.cloud.database()
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    
    // 今日订单数
    db.collection('orders')
      .where({
        createTime: db.command.gte(today)
      })
      .count()
      .then(res => {
        this.setData({
          'stats.todayCount': res.total
        })
      })
    
    // 待烹饪订单数
    db.collection('orders')
      .where({
        status: 'pending'
      })
      .count()
      .then(res => {
        this.setData({
          'stats.pendingCount': res.total
        })
      })
    
    // 已完成订单数
    db.collection('orders')
      .where({
        status: 'completed'
      })
      .count()
      .then(res => {
        this.setData({
          'stats.completedCount': res.total
        })
      })
  },

  // 切换标签
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ activeTab: tab })
  },

  // 标记完成
  onComplete(e) {
    const id = e.currentTarget.dataset.id
    const order = this.data.pendingOrders.find(item => item._id === id)
    
    wx.showModal({
      title: '确认完成',
      content: `确定订单"${order.orderNo}"已完成烹饪吗？`,
      success: res => {
        if (res.confirm) {
          this.markCompleted(id)
        }
      }
    })
  },

  // 执行标记完成
  markCompleted(id) {
    const db = wx.cloud.database()
    db.collection('orders')
      .doc(id)
      .update({
        data: {
          status: 'completed',
          completeTime: db.serverDate()
        }
      })
      .then(() => {
        wx.showToast({
          title: '操作成功',
          icon: 'success'
        })
        this.loadOrders()
        this.loadStats()
      })
      .catch(err => {
        console.error('操作失败：', err)
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        })
      })
  },

  // 添加备注
  onAddNote(e) {
    const id = e.currentTarget.dataset.id
    const order = this.data.pendingOrders.find(item => item._id === id)
    
    wx.showModal({
      title: '添加备注',
      editable: true,
      placeholderText: '请输入备注信息',
      success: res => {
        if (res.confirm && res.content) {
          this.updateNote(id, res.content)
        }
      }
    })
  },

  // 更新备注
  updateNote(id, note) {
    const db = wx.cloud.database()
    db.collection('orders')
      .doc(id)
      .update({
        data: {
          note: note
        }
      })
      .then(() => {
        wx.showToast({
          title: '备注已添加',
          icon: 'success'
        })
        this.loadOrders()
      })
  },

  // 查看订单详情
  onViewDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?id=' + id
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadOrders()
    this.loadStats()
    wx.stopPullDownRefresh()
  },

  // 跳转到身份验证
  goToAuth() {
    wx.switchTab({
      url: '/pages/home/home'
    })
  }
})